package cs422.group1.projectsquirrel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import java.io.File;
import java.text.DateFormat;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import java.util.Calendar;
import java.util.Date;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;



public class RecordObservation extends Activity
{	
	
	
	static final int TIME_DIALOG_ID = 0; // time dialog event id
	static final int DATE_DIALOG_ID = 1; // date dialog event id
	private int _hour, _minute, _year, _month, _day;
	private EditText _TimeField, _DateField, _GraySquirrelField, _FoxSquirrelField, _ZipCode; // references to field on screen
	private LocationManager locmgr;
	String _lat, _long;
	private Button _submit;
	
	
	
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        //setContentView(R.layout.shortsurvey);
	        setContentView(R.layout.testthis);
	        
	        _DateField = (EditText)findViewById(R.id.observationDate);
	        _TimeField = (EditText)findViewById(R.id.ObservationTime);
        	_GraySquirrelField = (EditText)findViewById(R.id.numGraySquirrels);
        	_FoxSquirrelField = (EditText)findViewById(R.id.numFoxSquirrels);
        	_ZipCode = (EditText)findViewById(R.id.zipcode);
        	_submit = (Button)findViewById(R.id.btnSubmit);
	        if (!ObservationDataManager.isEdit())
	        {
	        	locmgr = (LocationManager) getSystemService(LOCATION_SERVICE);
	        	locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GPSLocationListener());
	        	locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new GPSLocationListener());
	        	// prepopulate fields on screen
	        	Date today = new Date();
	        	
	        	_DateField.setText(DateFormat.getDateInstance().format(today));
	        	_TimeField.setText(DateFormat.getTimeInstance().format(today));
	        	_hour = today.getHours();
	        	_minute = today.getMinutes();
	        	_year = today.getYear() + 1900;
	        	_month = today.getMonth();
	        	_day = today.getDate();
	        	_submit.setText("Submit");	        		
	        }
	        else
	        {
	        	_TimeField.setText(ObservationDataManager.getData().observationTime);
	        	_DateField.setText(ObservationDataManager.getData().observationDate);
	        	_GraySquirrelField.setText(ObservationDataManager.getData().graySquirrels);
	        	_FoxSquirrelField.setText(ObservationDataManager.getData().foxSquirrels);
	        	_submit.setText("Next");
	        }
	}
	
	public void changeDate(View view)
	{
		showDialog(DATE_DIALOG_ID);
		
	}
	// create new event handler for the time selection dialog
	private TimePickerDialog.OnTimeSetListener _TimeSetListener =
		new TimePickerDialog.OnTimeSetListener()
	{
		//@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			_hour = hourOfDay;
			_minute = minute;
			updateDisplay();
			
		}
	};
	
	private DatePickerDialog.OnDateSetListener _DateSetListener = 
		new DatePickerDialog.OnDateSetListener()
	{

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			_year = year;
			_month = monthOfYear;
			_day  = dayOfMonth;
			updateDisplay();
			
		}
	};
	

		
	// override createDialog event
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, _TimeSetListener, _hour, _minute, false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, _DateSetListener, _year, _month, _day);
		}
		
		return null;
	}
	
	public void changeTime(View view)
	{
		showDialog(TIME_DIALOG_ID);
		
		final Calendar c = Calendar.getInstance();
		_hour = c.get(Calendar.HOUR_OF_DAY);
		_minute = c.get(Calendar.MINUTE);
		
		updateDisplay();
	}
	
	private void updateDisplay()
	{
		Date d = new Date();
		d.setDate(_day);
		d.setMonth(_month);
		d.setYear(_year);
		d.setHours(_hour);
		d.setMinutes(_minute);
		
		_TimeField.setText(DateFormat.getTimeInstance().format(d));
		

		_DateField.setText(DateFormat.getDateInstance().format(d));
	}
	
	public void submit(View view)
	{
		
		if (_FoxSquirrelField.getText().toString().equals(""))
		{
			Toast.makeText(this, "Please enter the number of Fox Squirrels observed", Toast.LENGTH_LONG).show();
			return;
		}
		
		if (_GraySquirrelField.getText().toString().equals(""))
		{
			Toast.makeText(this, "Please enter the number of Gray Squirrels observed", Toast.LENGTH_LONG).show();
			return;
		}
		try
		{
			if (Integer.parseInt(_ZipCode.getText().toString()) <= 9999 ||Integer.parseInt(_ZipCode.getText().toString()) >= 99999 )
			{
				Toast.makeText(this, "Please enter a valid zip code", Toast.LENGTH_LONG).show();
				return;
			}
		}
		catch (Exception e)
		{
			Toast.makeText(this, "Please enter a valid zip code", Toast.LENGTH_LONG).show();
			return;
		}
		
		
		// pull field data and store them
		ObservationData od = ObservationDataManager.getData();
		od.observationDate = _DateField.getText().toString();
		od.observationTime = _TimeField.getText().toString();
		od.latitude = _lat;
		od.longitude = _long;
		od.foxSquirrels = _FoxSquirrelField.getText().toString();
		od.graySquirrels = _GraySquirrelField.getText().toString();
		final Context context = this; // ref to current context -needed for methods below
		
		if (ObservationDataManager.getData().image == "")
		{
			// prompt user to take picture
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Would you like to include a picture with this observation?")
		       	.setCancelable(false)
		       	.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		       		public void onClick(DialogInterface dialog, int id) {
		       			capturePicture(context);
		       		}
		       	})
		       	.setNegativeButton("No", new DialogInterface.OnClickListener() {
		       		public void onClick(DialogInterface dialog, int id) {
		       			promptFullSurvey();
		       		}
		       	});
			AlertDialog alert = builder.create();
			alert.show();
		}
		else
		{
			promptFullSurvey();
		}
		
		
	}
	// prompts user to complete full survey
	private void promptFullSurvey()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Would you like to provide some additional data?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					continueSurvey();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						ObservationDataManager.getData().shortSurvey = true;
						ObservationDataManager.saveData(ObservationDataManager.getData());
						Toast.makeText(ProjectSquirrel.myAppContext, "Observation submitted.", Toast.LENGTH_LONG).show();
						Intent intent = new Intent(ProjectSquirrel.myAppContext, ProjectSquirrel.class);
						startActivity(intent);
				}
			});
		AlertDialog alert = builder.create();
		alert.show();
	}
			
	private void continueSurvey()
	{
		Intent intent = new Intent(this, ExtraSurvey.class);
		startActivity(intent);
	}
	
	// handles taking picture
	private void capturePicture(Context context)
	{
		final Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File fileName = getImageFile(context);
   		camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fileName) );
   		ObservationDataManager.getData().image = fileName.getAbsolutePath();
   		startActivityForResult(camera, 1);
	}
	// gets path to image file
	private File getImageFile(Context context)
	{
		  final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
		  if(!path.exists())
		  {
		    path.mkdir();
		  }
		  final String fileName = String.valueOf(new Date().hashCode()) + ".bmp";
		  return new File(path, fileName );
	}
	// called when camera returns
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		  if (resultCode == RESULT_OK) {
		    switch(requestCode){
		      case 1:
		        promptFullSurvey();
		      break;
		    }
		  }
		}

	

}
